<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <div class="editor-container" style="position: relative; padding-right: 20px; padding-bottom: 20px;">
      <Editor
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
        @onChange="updateHtml"
      />
      <div class="resize-handle" @mousedown="startResize"></div>
    </div>
  </div>
</template>
<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import 'katex/dist/katex.min.css'
import katex from 'katex'

import { onBeforeUnmount, ref, shallowRef, computed, onMounted ,watch} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Boot } from '@wangeditor/editor'
import formulaModule from '@wangeditor/plugin-formula'
import kityformula from "@/components/Editor/kityformula.js";
import MyModalMenu from "@/components/Editor/MyModelMenu.js";
  // 注册。要在创建编辑器之前注册，且只能注册一次，不可重复注册。
  Boot.registerModule(formulaModule)
  Boot.registerMenu(kityformula);
  const  myModel = {
      key: 'myMenu',
      factory() {
        return new MyModalMenu()
      }
  }
  Boot.registerMenu(myModel);

export default {
  components: { Editor, Toolbar },
  props: ['html'],
  setup(props,{ emit }) {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()
    // 内容 HTML
    const valueHtml = ref(typeof props.html === 'string' ? props.html : '')
  watch(props, (newValue) => {
  if (typeof newValue.html === 'string') {
    valueHtml.value = newValue.html
  }
})

   /** 当编辑器内容发生变化时的回调 */
   const updateHtml = (editor) => {
   emit('change', editor.getHtml())
   }

    const toolbarConfig = {
     toolbarKeys: [
          'undo', // 撤销
          'redo', // 重做
          'clearStyle', // 清除格式
          'headerSelect', // 标题
          'bold', // 加粗
          'italic', // 斜体
          'underline', // 下划线
          'justifyCenter', // 居中对齐
          'justifyJustify', // 两端对齐
          'justifyLeft', // 左对齐
          'justifyRight', // 右对齐
          'bulletedList', // 无序列表
          'numberedList', // 有序列表
          'color', // 文字颜色
          'insertLink', // 插入链接
          'fontSize', // 字体大小
          'fontFamily', // 字体
          'lineHeight', // 行高
          'uploadImage', // 上传图片
          'delIndent', // 缩进
          'indent', // 增进
          'divider', // 分割线
          'insertImage', // 网络图片
          'insertTable', // 插入表格 
          'codeBlock', // 代码段
          'fullScreen', // 全屏
      ],
      excludeKeys: [
          'bgColor', // 背景色
          'blockquote', // 引用
          'emotion', // 表情
          'through', // 删除线
          'deleteImage',//删除图片
      ],
       insertKeys: {
          index: 0,
          keys: [
          'insertFormula', // “插入公式”菜单
          // 'editFormula' // “编辑公式”菜单
          "kityFormula", // “编辑公式”菜单
          "myMenu"
          ],
},
    }
    const editorConfig = {
      placeholder: '请输入内容..',
        // 选中公式时的悬浮菜单
          hoverbarKeys: {
              formula: {
              menuKeys: [
                'editFormula'
              ], // “编辑公式”菜单
              },
          },

      MENU_CONF: {
        formula: {
          katex, // 配置 katex
          katexOptions: { displayMode: true }
        },
        uploadImage: {
          server: '/api/upload', // 上传API地址
          fieldName: 'file', // 上传文件字段名
          maxFileSize: 10 * 1024 * 1024, // 10M
          allowedFileTypes: ['image/*'],
          timeout: 5 * 1000, // 5秒
          meta: {
            token: 'your-token-here' // 可选的上传验证信息
          },
          onSuccess(file, res) {
            console.log('上传成功', file, res)
            return {
              url: res.url, // 上传后的图片 URL
              alt: file.name // 图片 alt 文本
            }
          },
          onProgress(progress) {
            console.log('上传进度', progress)
          },
          onFailed(file, res) {
            console.error('上传失败', file, res)
          },
          onError(file, err, res) {
            console.error('上传错误', file, err, res)
          }
        }
      }
}

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    /**
     * 处理编辑器创建后的逻辑
     */
    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    const startResize = (e) => {
      e.preventDefault();
      const textContainer = document.querySelector('.w-e-text-container');
      if (!textContainer) return;
      
      const startY = e.clientY;
      const startHeight = textContainer.offsetHeight;

      const handleMouseMove = (e) => {
        const deltaY = e.clientY - startY;
        const newHeight = startHeight + deltaY;
        // 限制最小和最大高度
        if (newHeight >= 100 && newHeight <= 800) {
          textContainer.style.height = `${newHeight}px`;
          const scrollContainer = textContainer.querySelector('.w-e-scroll');
          if (scrollContainer) {
            scrollContainer.style.height = `${newHeight - 20}px`;
          }
        }
      };

      const handleMouseUp = () => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
      };

      document.addEventListener('mousemove', handleMouseMove, { passive: true });
      document.addEventListener('mouseup', handleMouseUp, { passive: true });
    };
    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      updateHtml,
      startResize
    }
  },
}
</script>
<style>
::v-deep .w-e-text-container {
min-height: 300px !important;
max-height: 600px !important;
height: auto !important;
box-sizing: border-box !important;
}
.w-e-text-container .w-e-scroll {
min-height: 300px !important;
height: auto !important;
max-height: calc(100% - 20px) !important;
-webkit-overflow-scrolling: touch;
}
.resize-handle {
width: 20px;
height: 20px;
background: #f0f0f0;
border: 1px solid #ccc;
border-top: none;
border-left: none;
position: absolute;
right: 0;
bottom: 0;
cursor: se-resize;
box-shadow: 0 0 5px rgba(0,0,0,0.1);
z-index: 10;
}
.resize-handle::after {
display: none;
}
::v-deep .w-e-text-container .w-e-modal{
  min-width: 530px !important;

}

/* 整体容器 */
.symbol-selector-container {
    /* width: 400px; */
    /* height: 300px; */
    /* background: #fff; */
    /* border: 1px solid #ddd; */
    /* border-radius: 4px; */
    overflow: hidden;
    /* box-shadow: 0 6px 18px rgba(0,0,0,0.1); */
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 选项卡样式 */
.symbol-tabs {
    display: flex;
    background: #f8f8f8;
    border-bottom: 1px solid #ddd;
    padding: 0 5px;
}

.symbol-tab {
    padding: 6px 4px;
    cursor: pointer;
    font-size: 13px;
    color: #555;
    border-bottom: 2px solid transparent;
    transition: all 0.2s;
}

.symbol-tab:hover {
    background: #eaeaea;
    color: #333;
}

.symbol-tab.active {
    color: #2b579a;
    border-bottom: 2px solid #2b579a;
    font-weight: 600;
    background: #fff;
}

/* 内容区域 */
.symbol-content {
    height: calc(100% - 42px);
    overflow-y: auto;
    padding: 6px 4px;
    margin-bottom: 10px;
}

/* 符号网格 */
.symbol-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 1px; /* 网格线宽度 */
  background: #e0e0e0; /* 网格线颜色 */
  padding: 1px; /* 外边框支持 */
}

.symbol-grid > * {
  background: white; /* 单元格背景 */
}

/* 符号项 */
.symbol-item {
    /* border: 1px solid #e0e0e0; */
    /* border-radius: 4px; */
    /* margin-right: -1px; */
    /* margin-bottom: -1px; */
    text-align: center;
    cursor: pointer;
    transition: all 0.2s;
    background: #fff;
    overflow: hidden;
}

.symbol-item:hover {
    border-color: #2b579a;
    background: #f0f7ff;
    transform: translateY(-2px);
    box-shadow: 0 3px 8px rgba(43, 87, 154, 0.2);
}

/* 符号预览 */
.symbol-preview {
    font-size: 16px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    /* padding: 5px 0; */
}

/* 滚动条样式 */
.symbol-content::-webkit-scrollbar {
    width: 8px;
}

.symbol-content::-webkit-scrollbar-track {
    background: #f1f1f1;
}

.symbol-content::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.symbol-content::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}
</style>
